import preferences from '@ohos.data.preferences';
import ContextManager from './ContextManager';

const PREF_NAME = 'user_session';

export default class UserSessionManager {
  /**
   * 用户登录后，持久化保存登录状态、用户名和 token
   */
  static async login(username: string, token: string): Promise<void> {
    console.info('[UserSessionManager] login 入参:', username, token);
    const context = ContextManager.getContext();
    const pref = await preferences.getPreferences(context, PREF_NAME);
    await pref.put('isLoggedIn', 'true');
    await pref.put('username', username);
    await pref.put('token', token);
    await pref.flush();
    console.info('[UserSessionManager] token 已存储:', token);
  }

  /**
   * 用户退出登录后，清除持久化状态
   */
  static async logout(): Promise<void> {
    const context = ContextManager.getContext();
    const pref = await preferences.getPreferences(context, PREF_NAME);
    await pref.put('isLoggedIn', 'false');
    await pref.put('username', '');
    await pref.put('token', '');
    await pref.flush();
    console.info('[UserSession] 用户已退出登录，持久化状态已清除。');
  }

  /**
   * 检查用户是否已登录
   */
  static async isUserLoggedIn(): Promise<boolean> {
    // 开发调试时，始终返回未登录
    return false;
  }

  /**
   * 获取当前登录的用户名
   */
  static async getLoggedInUsername(): Promise<string> {
    const context = ContextManager.getContext();
    const pref = await preferences.getPreferences(context, PREF_NAME);
    const value = await pref.get('username', '');
    return String(value); // 强制转为字符串
  }

  /**
   * 获取 token
   */
  static async getToken(): Promise<string> {
    const context = ContextManager.getContext();
    const pref = await preferences.getPreferences(context, PREF_NAME);
    const value = await pref.get('token', '');
    return String(value); // 强制转为字符串
  }

  /**
   * 单独设置 token（如刷新 token 时）
   */
  static async setToken(token: string): Promise<void> {
    const context = ContextManager.getContext();
    const pref = await preferences.getPreferences(context, PREF_NAME);
    await pref.put('token', token);
    await pref.flush();
    console.log('[UserSessionManager] setToken 已保存:', token);
  }
}
